//
//  OKWebViewURLFilter.m
//  Onskysell
//
//  Created by cg on 17/3/6.
//  Copyright © 2017年 cg. All rights reserved.
//

#import "OKWebViewURLFilter.h"
#import "ShareHelp.h"
#import "LICGToast.h"
#import "CGLodingView.h"
#import "WebViewController.h"
#import "UuidManager.h"
#import <StoreKit/StoreKit.h>

@interface OKWebViewURLFilter () <SKStoreProductViewControllerDelegate>
@property (nonatomic, copy) NSString *payOrderId;//订单号
@property (nonatomic, strong) UIViewController *curCon;
@end

@implementation OKWebViewURLFilter

+ (OKWebViewURLFilter *)shared{
    static OKWebViewURLFilter *filter = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        filter = [[OKWebViewURLFilter alloc] init];
    });
    return filter;
}

- (BOOL)filter:(NSURLRequest *)request WebView:(WKWebView *)webview viewController:(UIViewController *)viewController{
    NSString *url = [request.URL absoluteString];
    if ([NSString isNullOrEmpty:url]) {
        return NO;
    }
    if ([self filterHandler:url WebView:webview viewController:viewController]) {
        return NO;
    }
    return YES;
}

- (BOOL)filterLoadingUrl:(NSString *)url
{
    if (url) {
        if ([LJUtility theString:url containSting:@"PaypalRedirect?OrderNo"] || [LJUtility theString:url containSting:@"www.paypal.com"]) {
            return NO;
        }
    }
    return YES;
}

- (BOOL)filterHandler:(NSString *)url WebView:(WKWebView *)webview viewController:(UIViewController *)viewController{
//    url = [LJUtility urlDecodedString:url];
    self.curCon = viewController;
//    NSString *webLoadUrl = webview.URL.absoluteString;
    
    //处理url为nil
//    if (url == nil || [url isEqualToString:@""]) {
//        url = webLoadUrl;
//    }
    
//    if ([LJUtility theString:webLoadUrl containSting:@"ossh52.cqlj023.com/Order/EnsureOrder"] && [LJUtility theString:webLoadUrl containSting:@"CartIDs="] && (url == nil || [url isEqualToString:@""])) {
//        url = webLoadUrl;
//    }
    
    //@"https://api.ggwuquan.com/Member/PersonalCenter"
    
    if ([LJUtility theString:url containSting:@"toAppScore"]) {
        if (@available(iOS 10.3, *)) {
             [self goScoreController];
        }
        else [self loadAppStoreControllerWithController:viewController];
        return YES;
    }
    
    if ([LJUtility theString:url containSting:@"tel:"]) {
        NSArray *temArr = [url componentsSeparatedByString:@"tel:"];
        NSString *phoneNum;
        if (temArr.count>1) {
            phoneNum = temArr[1];
            phoneNum = [phoneNum stringByReplacingOccurrencesOfString:@" " withString:@""];
        }
        NSMutableString *telPhone=[[NSMutableString alloc] initWithFormat:@"telprompt://%@",phoneNum];
        //            NSLog(@"str======%@",str);
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:telPhone]];
        return YES;
    }
    
    //分享
    if ([LJUtility theString:url containSting:@"ToShare"]) {
        url = [LJUtility urlDecodedString:url];
        NSArray *strArr = [url componentsSeparatedByString:@"toShare?"];
        NSString *paramStr, *shareTitle, *shareContent, *shareUrl, *shareImage;
        if (strArr.count==2) {
            paramStr = strArr[1];
            NSArray *paramsArr = [paramStr componentsSeparatedByString:@"&&"];
            if (paramsArr.count>0) {
                shareTitle = paramsArr[0];
                if (paramsArr.count>1) {
                    shareContent = paramsArr[1];
                    if (paramsArr.count>2) {
                        shareUrl = paramsArr[2];
                        if (paramsArr.count>3) {
                            shareImage = paramsArr[3];
                        }
                    }
                }
            }
        }
        
        if ([shareImage isEqualToString:@""]) {//处理一下后台没传图片又有&&分割符号导致shareImage取空字符串影响shareSDK分享排版的情况
            shareImage = nil;
        }
        [[ShareHelp shared] shareWithTitle:shareTitle content:shareContent image:shareImage url:shareUrl currentController:viewController fromType:FromNormalShare];
        return YES;
    }
    
    //相册选图
    if ([LJUtility theString:url containSting:@"SelectImg"]){
        __block NSString *imgPaths;
        imgPaths = nil;
        NSString *countStr = @"1";
        NSArray *tempArr = [url componentsSeparatedByString:@"?"];
        if (tempArr.count>1) {
            countStr = tempArr[1];//取最大图片数
        }
       
        TZImagePickerController *imagePC=[[TZImagePickerController alloc] initWithMaxImagesCount:countStr.integerValue delegate:nil];
        imagePC.allowPickingVideo = NO;
        imagePC.allowPickingOriginalPhoto = NO;
        
        [imagePC setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
            [[CGLodingView shareInstance] startAnimation];
            //创建多个线程用于填充图片
            __block int i = 0;
            
            for (UIImage *image in photos) {
                //异步执行队列任务
//                NSMutableDictionary *parms = [NSMutableDictionary dictionary];
                
                [CGNetManage httpPostImg:image compress:0.5 success:^(NSURLSessionDataTask *task, id responseObject) {
                    if ([responseObject isKindOfClass:[NSData class]]) {
                        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
                        if ([[[dic objectForKey:@"state"] objectForKey:@"code"] intValue] == 200) {
                            
                            NSArray *pathArr = [dic objectForKey:@"data"];
                            if (pathArr.count>0) {
                                if (imgPaths == nil) {
                                    imgPaths = pathArr.firstObject;
                                }
                                else{
                                    imgPaths = [NSString stringWithFormat:@"%@;%@",imgPaths,pathArr.count>0?pathArr.firstObject:@""];
                                }
                            }
                            
                            if (i == photos.count-1) {
                                dispatch_async(dispatch_get_main_queue(), ^{
                                    [[CGLodingView shareInstance] stopAnimation];
                                    NSString *jsSting = [NSString stringWithFormat:@"setImageToWeb('%@')",imgPaths];
                                    [[NSNotificationCenter defaultCenter]postNotificationName:JSKNotification object:jsSting];
                                });
                            }
                            i++;
                        }
                    }
                } fail:^(NSURLSessionDataTask *task, NSError *error) {
                    [[CGLodingView shareInstance] stopAnimation];
                    [LICGToast showWithText:@"图片上传失败" bottomOffset:ToastBottomOffset duration:2.0];
                }];
                
            }
        }];
        [viewController presentViewController:imagePC animated:YES completion:nil];//跳转
        return YES;
    }
    
    //获取deviceToken
    if ([LJUtility theString:url containSting:@"deviceToken"]) {
        NSString *token = [[NSUserDefaults standardUserDefaults]objectForKey:@"deviceToken"];
        NSString *jsSting = [NSString stringWithFormat:@"setTokenToWeb('%@')",token];
        [[NSNotificationCenter defaultCenter]postNotificationName:JSKNotification object:jsSting];
        return YES;
    }
    //Home/FirstIndex传deviceToken
//    if ([LJUtility theString:url containSting:@"Home/FirstIndex"] || [LJUtility theString:url containSting:@"Home/SecondIndex"] || [LJUtility theString:url containSting:@"Home/ThirdIndex"]) {
    
    /*不再用updateService方法,由web调GetCurrentDeviceID来唤我上传~!
    if ([url isEqualToString:BaseURL]) {
        
        NSString *deviceToken = [[NSUserDefaults standardUserDefaults] objectForKey:@"deviceToken"];
        NSString *jsSting = [NSString stringWithFormat:@"updateService('%@')",deviceToken];
        [[NSNotificationCenter defaultCenter] postNotificationName:JSKNotification object:jsSting];
        return NO;
    }
     */
    
    if ([LJUtility theString:url containSting:@"closeLoading"]) {
//        [OKWebViewURLFilter shared].endTimeMSecs = [[NSDate date] timeIntervalSince1970]*1000;
//        UInt64 timeDif = [OKWebViewURLFilter shared].endTimeMSecs-[OKWebViewURLFilter shared].startTimeMsecs;
//        NSString *timeDifStr = [NSString stringWithFormat:@"时间差%llu毫秒",timeDif];
//        [LICGToast showWithText:timeDifStr bottomOffset:ToastBottomOffset duration:2.0];
        
        [[CGLodingView shareInstance] stopAnimation];
        return YES;
    }
    
    if ([LJUtility theString:url containSting:@"goBack"]) {
//        if ([webLoadUrl rangeOfString:@"/Product/Detail" options:NSCaseInsensitiveSearch].location != NSNotFound || [webLoadUrl rangeOfString:@"/Order/Detail" options:NSCaseInsensitiveSearch].location != NSNotFound ) {//订单详情or产品详情直接pop不用判断
//            [viewController.navigationController popViewControllerAnimated:YES];
//        }
//        else {
            if ([webview canGoBack]) {
                if ([viewController isMemberOfClass:WebViewController.class]) {//处理返回需要load url带有新开web标识的会引起循环新开web的问题~!
                    WebViewController *vc = (WebViewController *)viewController;
                    vc.isNotFirstLoad = NO;
                }
                self.backNavigation = [webview goBack];
            }else{
                [viewController.navigationController popViewControllerAnimated:YES];
            }
//        }
        
        return YES;
    }
    
    if ([LJUtility theString:url containSting:@"closeweb"]) {
        [viewController.navigationController popViewControllerAnimated:YES];
        return YES;
    }
    
    if ([LJUtility theString:url containSting:@"returnHomeWeb"]) {//同时需要刷新
        [viewController.navigationController popToRootViewControllerAnimated:NO];
        [NotificationCenter postNotificationName:ReloadRootWebNoti object:nil];
        return YES;
    }
    
    
    //setHeaderColor状态栏背景色
    if ([LJUtility theString:url containSting:@"setHeaderColor"]) {
//        NSString *color = [NSString stringWithFormat:@"%@",[url valueWithURLParamName:@"color"]];
        NSString *color;
        NSArray *tempArr = [url componentsSeparatedByString:@"?"];
        if (tempArr.count==2) {
            color = tempArr[1];
        }
        [[NSNotificationCenter defaultCenter] postNotificationName:CHANGECOLORKNotification object:color];
        return YES;
    }
    //状态栏字前景色
    if ([LJUtility theString:url containSting:@"setStatusWordColor"]) {
//        NSString *color = [NSString stringWithFormat:@"%@",[url valueWithURLParamName:@"color"]];
        NSString *color;
        NSArray *tempArr = [url componentsSeparatedByString:@"?"];
        if (tempArr.count==2) {
            color = tempArr[1];
        }
        [[NSNotificationCenter defaultCenter] postNotificationName:CHANGEWORDCOLORNoti object:color];
        return YES;
    }
    
    
    //获取设备uuid
    if ([LJUtility theString:url containSting:@"GetCurrentDeviceID"]) {
        NSString *deviceToken = [[NSUserDefaults standardUserDefaults] objectForKey:@"deviceToken"];
        if (!deviceToken) deviceToken = @"";
        NSString *deviceUuid = [UuidManager getUUID];
        NSString *jsSting = [NSString stringWithFormat:@"SetCurrentServiceID('%@','%@')", deviceToken, deviceUuid];//发送给web推送devicetoken和设备uuid
        if (DebugMode) [LICGToast showWithText:[NSString stringWithFormat:@"设备号:%@",deviceUuid] bottomOffset:ToastBottomOffset];
        [[NSNotificationCenter defaultCenter] postNotificationName:JSKNotification object:jsSting];
        
        return YES;
    }
    
    //获取设备是否支持指纹支付,无参无返回值
    if ([LJUtility theString:url containSting:@"CheckFingerprint"]) {
        NSString *jsSting, *errorMsg;
        errorMsg = [LJUtility getSupportFingerprintIdentifyResult];
        if (!errorMsg) {//支持
            jsSting = @"SetIsFingerprint('1')";
            if (DebugMode) [LICGToast showWithText:@"支持指纹识别" bottomOffset:ToastBottomOffset duration:4.0];
        }
        else {
            jsSting = @"SetIsFingerprint('0')";
            if (DebugMode) [LICGToast showWithText:errorMsg bottomOffset:ToastBottomOffset duration:4.0];
        }
        [[NSNotificationCenter defaultCenter] postNotificationName:JSKNotification object:jsSting];
        
        return YES;
    }
    //请求指纹支付, 参数1: 随机码(字符串)
    if ([LJUtility theString:url containSting:@"GetFingerprint"]) {
        NSString *deviceUuid = [UuidManager getUUID];//设备号
        NSArray *tempArr = [url componentsSeparatedByString:@"GetFingerprint?"];
        NSString *randomStr, *isHaveRightBtn = @"1";//默认不带
        if (tempArr.count>1) {
            NSString *tempStr = tempArr[1];
            NSArray *tempArr2 = [tempStr componentsSeparatedByString:@"&&"];
            if (tempArr2.count>0) {
                randomStr = tempArr2[0];
                randomStr = [LJUtility md5:randomStr];//md5加密
                if (tempArr2.count>1) isHaveRightBtn = tempArr2[1];
            }
        }
        BOOL isWithRightBtn = [isHaveRightBtn isEqualToString:@"0"]?YES:NO;//0-要, 1-不要
        
        [LJUtility toVerifyFingerprintWithResult:^(NSString *error) {
            NSString *jsSting;
            if (!error) {//验证成功
                if (DebugMode) [LICGToast showWithText:@"指纹验证成功" bottomOffset:ToastBottomOffset duration:3.0];
                jsSting = [NSString stringWithFormat:@"SetFingerprintResult('1','%@','%@')",randomStr,deviceUuid];
            }
            else {//验证失败
                if (DebugMode) [LICGToast showWithText:error bottomOffset:ToastBottomOffset duration:4.0];
                jsSting = [NSString stringWithFormat:@"SetFingerprintResult('0','%@','%@')",randomStr,deviceUuid];
            }
            [[NSNotificationCenter defaultCenter] postNotificationName:JSKNotification object:jsSting];
        } isWithRightBtn:isWithRightBtn];
        return YES;
    }
    
    if ([LJUtility theString:url containSting:@"GetLogiInfo"]) {
        
        return YES;
    }
    
    if ([LJUtility theString:url containSting:@"jumpHomePage"]) {
        viewController.tabBarController.selectedIndex = 0;
        [viewController.navigationController popToRootViewControllerAnimated:YES];
        return YES;
    }
    
    /*
    //web提供的接口
     //告知设备号,参数1:设备号(字符串)
    if ([LJUtility theString:url containSting:@"SetCurrentServiceID"]) {
        
        return YES;
    }
     //告知是否支持指纹, 参数1(字符串): 1-是 0-否
    if ([LJUtility theString:url containSting:@"SetIsFingerprint"]) {
        
        return YES;
    }
    //告知指纹认证结果 - 参数1(字符串): 1通过 0未通过 ; 参数2: 随机码
    if ([LJUtility theString:url containSting:@"SetFingerprintResult"]) {
        
        return YES;
    }
     */
    
    return NO;
}

- (void)showLoadTimeDif
{
    [OKWebViewURLFilter shared].endTimeMSecs = [[NSDate date] timeIntervalSince1970]*1000;
    UInt64 timeDif = [OKWebViewURLFilter shared].endTimeMSecs-[OKWebViewURLFilter shared].startTimeMsecs;
    NSString *timeDifStr = [NSString stringWithFormat:@"web加载%llu毫秒",timeDif];
    [LICGToast showWithText:timeDifStr bottomOffset:ToastBottomOffset duration:2.0];
}

#pragma mark - 应用内appstore评分
//方法一:SKStoreReviewController简单好用直接弹出评分框,但要ios10.3以后才能用!
- (void)goScoreController
{
    [SKStoreReviewController requestReview];
}

//方法二:ios6以后就可以用,但相对SKStoreReviewController要六七秒后才弹出!
- (void)loadAppStoreControllerWithController:(UIViewController *)controller
{
    // 初始化控制器
    SKStoreProductViewController *storeProductViewContorller = [[SKStoreProductViewController alloc] init];
    
    // 设置代理请求为当前控制器本身
    
    storeProductViewContorller.delegate = self;
    
    [storeProductViewContorller loadProductWithParameters:@{SKStoreProductParameterITunesItemIdentifier:Appstore_AppId} completionBlock:^(BOOL result,NSError *error)   {
        if(error)  {
            NSLog(@"评分 error %@ with userInfo %@\n",error,[error userInfo]);
        }else{
            // 模态弹出appstore
            
            dispatch_async(dispatch_get_main_queue(), ^(void){
                [controller presentViewController:storeProductViewContorller animated:YES completion:nil];
            });
        }
    }];
    
}

//AppStore取消按钮监听
- (void)productViewControllerDidFinish:(SKStoreProductViewController*)viewController
{
    [viewController dismissViewControllerAnimated:YES completion:nil];
    
}
@end
